package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.util.GenericTokenParser;
import com.lagou.util.ParameterMapping;
import com.lagou.util.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: lcz
 * @date: Created in 13:21 2020/9/26
 * @description:
 */
public class SimpleExecutor implements Executor {
    private Connection connection;

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement statement, Object... params) throws Exception {
        PreparedStatement preparedStatement = getPreparedStatement(configuration, statement, params);
        //执行sql，获取结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        //得到返回结果class
        Class<?> resultType = statement.getResultType();
        ArrayList<Object> results = new ArrayList<>();
        //遍历结果集
        while (resultSet.next()) {
            Object obj = resultType.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //结果对象属性个数
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                //属性名
                String columnName = metaData.getColumnName(i);
                //属性值
                Object value = resultSet.getObject(columnName);
                //使用反射或内省，根据数据库表和实体的对应关系，完成封装，创建属性描述器（内省库中的），为属性生成读写方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                //获取写方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                //向类中写入值
                writeMethod.invoke(obj, value);
            }
            //封装为返回结果类型
            results.add(obj);
        }
        return (List<E>) results;
    }

    @Override
    public int executeUpdate(Configuration configuration, MappedStatement statement, Object... params) throws Exception {
        PreparedStatement preparedStatement = getPreparedStatement(configuration, statement, params);
        return preparedStatement.executeUpdate();
    }

    @Override
    public void close() throws SQLException {
        connection.close();
    }

    /**
     * @author: lcz
     * @date: Created in 14:27 2020/9/26
     * @description: 完成对#{}的解析工作：1、将#{}使用？进行替代，2、解析出#{}里面的值进行存储
     */
    private BoundSql getBoundSql(String mapperSql) {
        //利用mybatis现有的标记处理类：主要是配合通用标记解析器GenericTokenParser完成对配置文件等解析工作，其中TokenHandler主要完成处理
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        //GenericTokenParser：通用的标记解析器，完成了代码片段中的占位符的解析，然后再根据给定的标记处理器(TokenHandler)来进行表达式的处理
        // 三个参数：分别为openToken (开始标记)、closeToken (结束标记)、handler (标记处 理器)
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        //此处的sql占位符已经被转换为?
        String sql = genericTokenParser.parse(mapperSql);
        //解析得到的#{}中的参数名称
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();
        return new BoundSql(sql, parameterMappings);
    }

    /**
     * @author: lcz
     * @date: Created in 15:38 2020/9/26
     * @description: 获取预处理对象preparedStatement
     */
    private PreparedStatement getPreparedStatement(Configuration configuration, MappedStatement statement,
                                                   Object... params) throws Exception {
        connection = configuration.getDataSource().getConnection();
        //获取sql语句，得到的是select * from user where id=#{id}，需要处理成jdbc能识别的sql，即，占位符用?
        String mapperSql = statement.getSql();
        BoundSql boundSql = getBoundSql(mapperSql);
        String sql = boundSql.getSql();
        //获取预处理对象preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //获取sql查询参数class
        Class<?> parameterType = statement.getParameterType();
        //设置参数
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String name = parameterMapping.getName();
            //使用反射
            Field declaredField = parameterType.getDeclaredField(name);
            declaredField.setAccessible(true);
            //获取参数值
            Object paramValue = declaredField.get(params[0]);
            //对应占位符赋值
            preparedStatement.setObject(i + 1, paramValue);
        }
        return preparedStatement;
    }
}
